import re
import urllib2
from codes import *
import conf

class CbrRateLoader(object):
    #<tr bgcolor="#ffffff"><td align="right" >36</td>
    #<td align="left" >&nbsp;&nbsp;AUD<td align="right" >1</td>
    #<td>&nbsp;&nbsp;Австралийский доллар</td>
    #<td align="right">14,8100</td></tr>

    _re_currency = re.compile(
        '''<tr bgcolor="#ffffff"><td align="right" >(\d+)(?:</td>)?\s*'''
        '''<td align="left" >(?:&nbsp;)*[^<]+(?:</td>)?\s*<td align="right" >(\d+)(?:</td>)?\s*'''
        '''<td>(?:&nbsp;)*[^<]+(?:</td>)?\s*'''
        '''<td align="right">(\d+,\d+)(?:</td>)?</tr>'''
    )

    MIN_YEAR = 1992
    BASE_CURRENCY = RUB

    def __call__(self, date):
        """
        Return list of:
        (source_quantity, source_currency, target_quantity, target_currency)
        """
        url = 'http://cbr.ru/currency_base/D_print.aspx?date_req=%02d.%02d.%d'
        html = urllib2.urlopen(url % (date.day, date.month, date.year)).read()
#        open('t.html', 'w').write(html)
#        html = open('t.html', 'r').read()
#        print 'html=',html

        if date.year < conf.FIRST_DENOMINATION_YEAR:
             process_value = lambda v: float(v.replace(',', '.')) / 1000
        else:
             process_value = lambda v: float(v.replace(',', '.'))

        res = [(int(quantity), int(code), process_value(value), self.BASE_CURRENCY)
            for code, quantity, value in self._re_currency.findall(html)]
        print 'res = ', res
        return res
